package com.weetop.aklyscan.activity;

import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseFragment;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.FittingInfo;
import com.weetop.aklyscan.bean.InStockItemBean;
import com.weetop.aklyscan.bean.TransferBoxBean;
import com.weetop.aklyscan.presenter.ZxPeiJianPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.utils.widget.MyDialogUtil;
import com.weetop.aklyscan.view.ZxPeiJianView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class Fragment_pj_th extends BaseFragment<ZxPeiJianPresent> implements ZxPeiJianView {
    private static final int HUOJIA_CODE = 12000;
    private static final int REQUEST_HUOJIA_CODE_SCAN_ONE = 22000;
    String xiangCode;

    @BindView(R.id.rcy_product)
    RecyclerView rcyProduct;
    Unbinder unbinder;
    @BindView(R.id.et_zzx_code)
    TextView etZzxCode;
    @BindView(R.id.btn_save)
    QMUIButton btnSave;
    @BindView(R.id.bianma)
    TextView bianma;
    @BindView(R.id.peijian_no)
    TextView peijian_no;
    @BindView(R.id.peijian_num)
    TextView peijian_num;
    @BindView(R.id.add)
    TextView add;
    private CommonRecyclerAdapter<InStockItemBean> adapter;
    private List<InStockItemBean> list = new ArrayList<>();
    private int alreadyInStockCount;
    private String barcode;
    private String boxCode;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                peijian_no.setText((String) msg.obj);
                peijian_no.setBackgroundResource(R.drawable.et_grey);
            }
        }
    };

    @Override
    protected ZxPeiJianPresent createPresenter() {
        return new ZxPeiJianPresent(this, getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_peijian, null);
        unbinder = ButterKnife.bind(this, view);
        rcyProduct.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonRecyclerAdapter<InStockItemBean>(mActivity, R.layout.item_peijian, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InStockItemBean item, int position) {
                helper.setText(R.id.tv_id, position + 1 + "");
                helper.setText(R.id.tv_code, item.getGoods_code());
                String product_name = TextUtils.isEmpty(item.getGoods_name()) ? "-" : item.getGoods_name();
                helper.setText(R.id.tv_name, product_name);

                TextView etCount = helper.getView(R.id.tv_number);
                if (item.getCount() != 0) {
                    etCount.setText(item.getCount() + "");
                } else {
                    //产品无数量概念
                    etCount.setText("");
                }
//                if (item.getStatus() == 0) {
                //产品数量不可修改
//                    setEditTextEnable(etCount, true);
                helper.setVisible(R.id.btn_remove, View.VISIBLE);
                helper.setOnClickListener(R.id.btn_remove, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (BaseUtils.fastClick()) {
                            list.remove(position);
                            adapter.remove(position);
                        }
                    }
                });
//                    etCount.addTextChangedListener(new TextWatcher() {
//                        @Override
//                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                            Log.e("TAG", "beforeTextChanged: " + s.toString());
//                        }
//
//                        @Override
//                        public void onTextChanged(CharSequence s, int start, int before, int count) {
//                            Log.e("TAG", "onTextChanged: " + s.toString());
//                        }
//
//                        @Override
//                        public void afterTextChanged(Editable s) {
//                            Log.e("TAG", "afterTextChanged: " + s.toString());
//                            String editText = s.toString().trim();
//                            if (!TextUtils.isEmpty(editText)) {
//                                InStockItemBean inStockItemBean = list.get(position);
//                                Integer value = Integer.valueOf(editText);
//                                inStockItemBean.setCount(value);
//                                list.remove(position);
//                                list.add(position, inStockItemBean);
//                            }
//                        }
//                    });
//                } else {
////                    setEditTextEnable(etCount, false);
//                    helper.setVisible(R.id.btn_remove, View.INVISIBLE);
//                }
            }
        };
        rcyProduct.setAdapter(adapter);

        return view;
    }

    @Override
    public void getSearchResultSuccess(BaseModel<TransferBoxBean> o) {
        TransferBoxBean data = o.getData();
        barcode = data.getBarcode();
        etZzxCode.setText(barcode);
//        etCkName.setText(data.getTier_name());
//        etCkPostion.setText(data.getTier_code());
        List<TransferBoxBean.ItemsBean> items = data.getItems();
        list.clear();
        if (items != null && items.size() > 0) {
            for (int i = 0; i < items.size(); i++) {
                TransferBoxBean.ItemsBean item = items.get(i);
                //产品类型：1产品；2配件
                if (item.getProduct_type() == 2) {
                    InStockItemBean goodsItems = new InStockItemBean();
                    goodsItems.setGoods_code(item.getProduct_code());
                    goodsItems.setGoods_name(item.getProduct_name());
                    goodsItems.setGoods_type(item.getProduct_type());
                    goodsItems.setCount(item.getNumber());
                    //状态:-1已作废；0未入库；1在库里；2未出库；3已出库
                    goodsItems.setStatus(1);
                    list.add(goodsItems);
                }
            }
        }
        alreadyInStockCount = list.size();
        adapter.replaceAll(list);
    }

    @Override
    public void getFittingInfoSuccess(BaseModel<FittingInfo> o) {
        FittingInfo data = o.getData();
        InStockItemBean goodsItems = new InStockItemBean();
        goodsItems.setGoods_code(data.getMatter_code());
        goodsItems.setGoods_name(data.getMatter_name());
        goodsItems.setGoods_id(data.getMatter_id());
        //产品类型：1产品；2配件
        goodsItems.setGoods_type(2);
        goodsItems.setCount(1);
        //状态:-1已作废；0未入库；1在库里；2未出库；3已出库
        goodsItems.setStatus(0);
        list.add(goodsItems);
        adapter.add(goodsItems);
    }

    @Override
    public void saveZxSuccess(BaseModel<Object> o) {
        etZzxCode.setText(xiangCode);
        etZzxCode.setBackgroundResource(R.drawable.et_grey);
        if (TextUtils.isEmpty(peijian_no.getText().toString().trim())) {
            peijian_no.setBackgroundResource(R.drawable.et_yellow);
        } else {
            peijian_no.setBackgroundResource(R.drawable.et_grey);
        }
        playRing("shujuyouxiao.mp3");
    }

    @Override
    public void getInto02Success(BaseModel<Object> o) {
    }

    @Override
    public void getInto07Success(BaseModel<FittingInfo> o) {
        FittingInfo fittingInfo = o.getData();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getGoods_code().equalsIgnoreCase(peijian_no.getText().toString().trim())) {
                list.get(i).setCount(list.get(i).getCount() + Integer.valueOf(peijian_num.getText().toString().trim()));
                adapter.notifyDataSetChanged();
                return;
            }
        }
        InStockItemBean inStockItemBean = new InStockItemBean();
        inStockItemBean.setGoods_id(fittingInfo.getMatter_id());
        inStockItemBean.setGoods_code(fittingInfo.getMatter_code());
        inStockItemBean.setGoods_name(fittingInfo.getMatter_name());
        inStockItemBean.setCount(Integer.valueOf(peijian_num.getText().toString().trim()));
        list.add(inStockItemBean);
        adapter.add(inStockItemBean);
    }

    @Override
    public void getInto09Success(BaseModel<Object> o) {
        ToastUtil.getInstance()._short(getActivity(), "操作成功");
        list.clear();
        adapter.clear();
        adapter.notifyDataSetChanged();
        etZzxCode.setText("");
        peijian_no.setText("");
        peijian_num.setText("");
        playRing("zhuangxiangwancheng.mp3");

    }

    @Override
    public void onDataError() {

    }

    @Override
    public void onUpFail(String mag) {
        MyDialogUtil.showDialog(getActivity(), mag);
        playRing("wuxiao.mp3");
    }

    /**
     * 设置EditText是否可编辑
     *
     * @param editText 设置的editText对象
     * @param enable   是否可编辑
     */
    private void setEditTextEnable(EditText editText, boolean enable) {
        if (enable) {
            editText.setFocusableInTouchMode(true);
            editText.setFocusable(true);
            editText.requestFocus();
        } else {
            editText.setFocusable(false);
            editText.setFocusableInTouchMode(false);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.btn_save, R.id.qingkong, R.id.add, R.id.qingkong1})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_save:
                try {
                    if (TextUtils.isEmpty(etZzxCode.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(getActivity(), "中转箱编码不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(peijian_no.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(getActivity(), "配件编号不能为空");
                        return;
                    }
                    if (BaseUtils.fastClick()) {
                        JSONArray jsonArray = new JSONArray();
                        JSONObject tmpObj = null;
                        for (int i = 0; i < list.size(); i++) {
                            tmpObj = new JSONObject();
                            tmpObj.put("serial_code", list.get(i).getGoods_code());
                            tmpObj.put("goods_model", list.get(i).getGoods_code());
                            tmpObj.put("goods_name", list.get(i).getGoods_name());
                            tmpObj.put("num", list.get(i).getCount());
                            jsonArray.put(tmpObj);
                            tmpObj = null;
                        }
                        if (list.size() > 0) {
                            mPresenter.Into09(peijian_no.getText().toString().trim(),"1", etZzxCode.getText().toString().trim(), jsonArray);
                        } else {
                            ToastUtils.showShort("无新增配件");
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.qingkong:
                etZzxCode.setText("");
                playRing("qingkong.mp3");
                etZzxCode.setBackgroundResource(R.drawable.et_yellow);
                peijian_no.setBackgroundResource(R.drawable.et_grey);
                break;
            case R.id.qingkong1:
                peijian_no.setText("");
                playRing("qingkong.mp3");
                if (TextUtils.isEmpty(etZzxCode.getText().toString().trim())) {
                    peijian_no.setBackgroundResource(R.drawable.et_grey);
                } else {
                    peijian_no.setBackgroundResource(R.drawable.et_yellow);
                }
                break;
            case R.id.add:
                if (TextUtils.isEmpty(peijian_no.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(getActivity(), "配件编号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(peijian_num.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(getActivity(), "配件数量不能为空");
                    return;
                }
                mPresenter.Into07(peijian_no.getText().toString().trim());
                break;
        }
    }

    public void onBarcodeEvent(String code) {
        System.out.println("扫描结果1：" + code);
        if (TextUtils.isEmpty(etZzxCode.getText().toString().trim())) {
            xiangCode = code;
            mPresenter.saveZx(code);
        } else if (TextUtils.isEmpty(peijian_no.getText().toString().trim())) {
            Message message = new Message();
            message.what = 1;
            message.obj = code;
            handler.sendMessage(message);
        }
    }

    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();

    private void playRing(String fileName) {
        try {
            assetManager = getActivity().getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName)) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    if (i == 1) {
                        playRing("luruchenggong.mp3");
                    } else {
                        playRing("wuxiao.mp3");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        if (player.isPlaying()) {
            player.stop();
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        player.release();
        super.onDestroy();
    }
}
